package com.fowo.api.user.controller;

import com.fowo.api.common.model.R;
import com.fowo.api.sys.service.SysUserService;
import com.fowo.api.user.model.*;
import com.fowo.api.user.service.LoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Tag(name = "登录控制器")
@RequestMapping("/api")
@RestController
public class LoginController {

    @Resource
    private LoginService loginService;
    @Resource
    private SysUserService sysUserService;

    @Operation(summary = "请求获取短信验证码")
    @GetMapping("login/captcha")
    public R getCaptcha(@Validated GetCaptchaModel model) {
        return loginService.createCaptcha(model.getPhone());
    }

    @Operation(summary = "平台登录")
    @PostMapping("login/account")
    public LoginResult account(@Validated @RequestBody LoginAccount loginAccount) {
        if(LoginAccount.TYPE_ACCOUNT.equals(loginAccount.getType())) {
            return loginService.loginByAccount(loginAccount);
        } else if(LoginAccount.TYPE_MOBILE.equals(loginAccount.getType())) {
            return loginService.loginByCaptcha(loginAccount);
        } else {
            return new LoginResult();
        }
    }

    @Operation(summary = "取当前登录用户信息")
    @GetMapping("currentUser")
    public R<CurrentUser> currentUser(JwtUserInfo jwtUserInfo) {
        if (jwtUserInfo != null) {
            if ("ADMIN".equals(jwtUserInfo.getType())) {
                return R.data(sysUserService.getCurrentUserById(jwtUserInfo.getUserId()));
            }
        }
        return R.fail("用户未登录！");
    }

    @Operation(summary = "Token 续约", description = "读取当前 token 返回新的 Token")
    @GetMapping("login/renewToken")
    public R<LoginResult> renewToken(JwtUserInfo jwtUserInfo) {
        return R.data(loginService.renewToken(jwtUserInfo));
    }

    @Operation(summary = "退出登录")
    @PostMapping("login/outLogin")
    public R outLogin() {
        // 当前不做什么操作
        return R.ok(true);
    }
}
